package cn.wawi.controller.sys;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import cn.wawi.common.Json;
import cn.wawi.common.annotation.Permission;
import cn.wawi.common.easyui.DataGrid;
import cn.wawi.common.easyui.Tree;
import cn.wawi.controller.BaseController;
import cn.wawi.entity.sys.Privilege;
import cn.wawi.utils.QueryUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/sys_privilege")
public class PrivilegeController extends BaseController<Privilege>{
	
	@Permission("sys:privilege:menu:view")
	@RequestMapping(value="/menu",method=RequestMethod.GET)
	public String menu() {
		return "sys/privilege/menu";
	}
	/**
	 *  菜单列表
	 */
	@ResponseBody
	@RequestMapping(value="/menuList",method=RequestMethod.GET)
	public DataGrid menuList(HttpServletRequest request){
		Map<String,Object> map=QueryUtil.setNoPage(request);
		map.put("type", "F");
		List<Privilege> list = privilegeDao.findAll(map);
		DataGrid dataGrid=new DataGrid(list,list.size()+0L);
		return dataGrid;
	}
	/**
	 * 权限列表
	 */
	@ResponseBody
	@RequestMapping(value="/list",method=RequestMethod.GET)
	public DataGrid list(HttpServletRequest request){
		Map<String,Object> map=QueryUtil.setPage(request);
		map.put("type", "O");
		List<Privilege> list = privilegeDao.findAll(map);
		PageInfo<Privilege> pages = new PageInfo<Privilege>(list);
		DataGrid dataGrid=new DataGrid(pages.getList(),pages.getTotal());
		return dataGrid;
	}

	@ResponseBody
	@RequestMapping(value="/getMenu",method=RequestMethod.GET)
	public List<Tree> getMenu(HttpServletRequest request){
		List<Privilege> list = privilegeDao.findMenu(null);
		return trees(list);
	}
	
	public List<Tree> trees(List<Privilege> list){
		List<Tree> trees=new ArrayList<Tree>();
		for(Privilege d: list){
			if("F".equals(d.getType())){
				Tree tree=new Tree(d.getId(), d.getName());
				tree.setChildren(trees(d.getChildren()));
				tree.setIconCls(d.getIconCls());
				trees.add(tree);
			}
		}
		return trees;
	}
	@ResponseBody
	@RequestMapping(value="/addPermission",method=RequestMethod.GET)
	public Json addPermission(Long pId){
		privilegeDao.save(new Privilege("添加","add","添加",pId));
		privilegeDao.save(new Privilege("删除","delete","删除",pId));
		privilegeDao.save(new Privilege("修改","update","修改",pId));
		privilegeDao.save(new Privilege("查看","view","查看",pId));
		return new Json("addPermission", "添加基本权限");
	}
}
